package com.zyy.java8.samples.lambda;

import java.util.Comparator;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author zhangyiying
 * @ClassName: Lambda3
 * @Description: 函数式接口
 * @date 2021/12/24 17:09
 */
public class Lambda3 {

    @FunctionalInterface
    interface Fun {
        void foo();
    }

    public static void main(String[] args) throws Exception {

        /**
         * Predicates 《T》： 断言型接口，有参有返回值，返回值是boolean类型
         */
        Predicate<String> predicate = (s) -> s.length() > 0;
        boolean test1 = predicate.test("foo");
        // true
        System.out.println(test1);
        boolean test2 = predicate.negate().test("foo");
        // false
        System.out.println(test2);

        Predicate<Boolean> nonNull = Objects::nonNull;
        Predicate<Boolean> isNull = Objects::isNull;

        Predicate<String> isEmpty = String::isEmpty;
        Predicate<String> isNotEmpty = isEmpty.negate();

        /**
         * Functions 《T,R》：函数式接口，有参有返回值
         */
        Function<String, Integer> toInteger = Integer::valueOf;
        Function<Integer, String> toString = String::valueOf;
        Function<String, String> backToString = toInteger.andThen(toString);

        //  "123" 先执行toInteger再执行toString 最终返回一个String字符串
        System.out.println(backToString.apply("123"));

        /**
         * Suppliers 《T》：供给型接口，无参有返回值
         */
        Supplier<Person> personSupplier = Person::new;
        //new Person
        personSupplier.get();

        /**
         * Consumers 《T》：消费型接口，有参无返回值
         */
        Consumer<Person> personConsumer = (p) -> System.out.println("Hello, " + p.firstName);
        personConsumer.accept(new Person("Tom", "Justin"));

        /**
         * Comparators
         */
        Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);

        Person p1 = new Person("John", "Doe");
        Person p2 = new Person("Alice", "Wonderland");

        // > 0
        comparator.compare(p1, p2);
        // < 0
        comparator.reversed().compare(p1, p2);

        /**
         * Runnables
         */
        Runnable runnable = () -> System.out.println(UUID.randomUUID());
        runnable.run();

        /**
         * Callables
         */
        Callable<UUID> callable = UUID::randomUUID;
        callable.call();

    }

}
